local blaze = require "blaze"
local app = require "app"
local game = app.game.running

local M = game.ui.activity()

local function sort_by_chip(a, b)
    return a.chip > b.chip
end

function M:ctor()
    local SimpleList = require "blaze.ui.widget.SimpleList"
    local PlayerListItem = require "club.threecard.baccaratlib.ui.playerlist.PlayerListItem"
    self.res = "club.threecard.baccaratlib/ui/common.b:PlayerListUI"
    self.list = SimpleList.new()
    self.list.create_item = function(_, data, index)
        return PlayerListItem.new(data, index)
    end
end

function M:on_injected(bind)
    bind("button.click", self.btn_close, self.on_close)
    bind("button.click", self.close_mask, self.on_close)
    self.list:set_parent(self.content)
end

function M:on_close()
    self:hide()
end

function M:on_load()
    self:super("on_load")
    self.list:load()
end

function M:show()
    self:super("show")
    local players = {}
    for _, player in pairs(game.store.room.state.players) do
        table.insert(players, player)
    end
    table.sort(players, sort_by_chip)
    self.list:fill(players)
end

function M:on_release()
    self:super("on_release")
    self.list:release()
end

return M